package com.smile.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.smile.api.OperateLogApi;
import com.smile.api.OrganizationApi;
import com.smile.api.OssApi;
import com.smile.commons.action.ActionUtils;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.commons.page.R;
import com.smile.commons.time.TimeUtils;
import com.smile.mapper.AirportDroneMapper;
import com.smile.mapper.AirportInfoMapper;
import com.smile.mapper.AirportMapper;
import com.smile.mapper.DroneMapper;
import com.smile.model.domain.FeisuanAirport;
import com.smile.model.domain.FeisuanAirportDrone;
import com.smile.model.domain.FeisuanAirportInfo;
import com.smile.model.domain.FeisuanDrone;
import com.smile.model.dto.DroneDTO;
import com.smile.model.dto.request.*;
import com.smile.model.request.GetOrganizationByIdRequest;
import com.smile.model.response.GetOrganizationByIdResponse;
import com.smile.model.response.response.GetAirportByIdResponseDTO;
import com.smile.model.response.response.GetAirportInfoResponseDTO;
import com.smile.model.response.response.GetAirportListResponseDTO;
import com.smile.request.AddOperateLogRequest;
import com.smile.service.AirportInfoService;
import com.smile.service.AirportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AirportInfoServiceImpl implements AirportInfoService {

    @Autowired
    private OssApi ossApi;

    @Autowired
    private AirportMapper airportMapper;

    @Autowired
    private AirportInfoMapper airportInfoMapper;

    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private AirportDroneMapper airportDroneMapper;

    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private OrganizationApi organizationApi;

    private ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    @Transactional
    public Boolean addAirportInfo(AddAirportInfoRequestDTO addAirportInfoRequestDTO) throws IOException {
        try {
            reentrantLock.lock();

            Long startTime = System.nanoTime();

            // 1. 创建机场对象并设置基础属性
            FeisuanAirportInfo feisuanAirportInfo = new FeisuanAirportInfo();
            BeanUtil.copyProperties(addAirportInfoRequestDTO, feisuanAirportInfo);

//        // 2. 处理机场图片
//        String fileName = IdWorker.getIdStr() + ".jpg";
//        R<PutFileResponse> putFileResponseR = ossApi.putFile("photo/airport", fileName, addAirportRequestDTO.getAirportImage());
//
//        // 修正图片上传判断逻辑
//        if (putFileResponseR != null && putFileResponseR.getCode() == 200 && putFileResponseR.getData() != null) {
//            feisuanAirport.setAirportImageUrl(fileName);
//        } else {
//            // 可以添加日志记录上传失败，或使用默认图片
//            log.error("机场图片上传失败: {}", putFileResponseR);
//        }

            // 3. 设置其他属性
            feisuanAirportInfo.setCreateTime(LocalDateTime.now());
            feisuanAirportInfo.setModifyTime(LocalDateTime.now());
//            feisuanAirportInfo.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));

//            feisuanAirportInfo.setTotalTaskCount(0L);
//            feisuanAirportInfo.setTotalTaskTime(0L);
            feisuanAirportInfo.setDeleteStatus(false);
//            feisuanAirportInfo.setTotalTaskDistance(0L);

            // 4. 保存机场信息
            airportInfoMapper.insert(feisuanAirportInfo);

//            // 5. 处理关联的无人机（新增绑定状态检查）
//            List<Long> droneIds = addAirportRequestDTO.getDroneIds();
//            if (CollUtil.isNotEmpty(droneIds)) {
//                // 5.1 检查无人机绑定状态
//                QueryWrapper<FeisuanAirportDrone> bindCheckWrapper = new QueryWrapper<>();
//                bindCheckWrapper.in("drone_id", droneIds)
//                ; // 假设0表示未删除
//
//                List<FeisuanAirportDrone> existingBinds = airportDroneMapper.selectList(bindCheckWrapper);
//
//                // 5.2 收集已绑定的无人机ID
//                Set<Long> boundDroneIds = existingBinds.stream()
//                        .map(FeisuanAirportDrone::getDroneId)
//                        .collect(Collectors.toSet());
//
//                // 5.3 找出未绑定的无人机
//                List<Long> validDroneIds = droneIds.stream()
//                        .filter(droneId -> !boundDroneIds.contains(droneId))
//                        .collect(Collectors.toList());
//
//                // 5.4 如果有重复绑定，记录日志或抛出异常
//                if (validDroneIds.size() != droneIds.size()) {
//                    log.warn("检测到{}架无人机已绑定，跳过绑定: {}",
//                            droneIds.size() - validDroneIds.size(),
//                            droneIds.stream()
//                                    .filter(boundDroneIds::contains)
//                                    .collect(Collectors.toList()));
//                }
//
//                // 5.5 只保存未绑定的无人机
//                if (CollUtil.isNotEmpty(validDroneIds)) {
//                    List<FeisuanAirportDrone> relations = validDroneIds.stream()
//                            .map(droneId -> {
//                                FeisuanAirportDrone relation = new FeisuanAirportDrone();
//                                relation.setAirportId(feisuanAirport.getId());
//                                relation.setDroneId(droneId);
////                            relation.(false); // 设置删除状态
//                                return relation;
//                            })
//                            .collect(Collectors.toList());
//
//                    // 批量保存关联关系
//                    Db.saveBatch(relations);
//                }
//            }
//
//            // 6. 记录操作日志
//            Long endTime = System.nanoTime();
//            AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
//            addOperateLogRequest.setOperateModule("设备模块");
//            addOperateLogRequest.setOperateName("新增机场");
//            addOperateLogRequest.setOperateResult(Boolean.TRUE);
//            addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
//            addOperateLogRequest.setOperateType(1);
//            addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
//            addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
//            addOperateLogRequest.setTimes(endTime - startTime);
//            operateLogApi.addOperateLogRequest(addOperateLogRequest);

        } finally {
            reentrantLock.unlock();
        }

        return Boolean.TRUE;
    }

//    @Override
//    public Page<GetAirportListResponseDTO> getAirportList(GetAirportListRequestDTO getAirportListRequestDTO) {
//        QueryWrapper<FeisuanAirport> queryWrapper = new QueryWrapper<>();
//        if (ObjectUtil.isNotNull(getAirportListRequestDTO)) {
//            if (ObjectUtil.isNotNull(getAirportListRequestDTO.getStatus())) {
//                queryWrapper.eq("status", getAirportListRequestDTO.getStatus());
//            }
//            if (StrUtil.isNotBlank(getAirportListRequestDTO.getAirportName())) {
//                queryWrapper.eq("airport_name", getAirportListRequestDTO.getAirportName());
//            }
//        }
//        Page<FeisuanAirport> page = airportMapper.selectPage(new Page<>(getAirportListRequestDTO.getCurrentPage(), getAirportListRequestDTO.getPageSize()), queryWrapper);
//
//
//        Page<GetAirportListResponseDTO> getAirportListResponseDTOPage = MyBatisPlusPageConverter.convertPage(page, GetAirportListResponseDTO.class);
//
//        List<Long> collect = page.getRecords().stream().map(i -> i.getId()).collect(Collectors.toList());
//
//        List<FeisuanAirportDrone> feisuanAirportDrones = new ArrayList<>();
//
//        if (CollectionUtil.isNotEmpty(collect)){
//
//            QueryWrapper<FeisuanAirportDrone> feisuanAirportDroneQueryWrapper = new QueryWrapper<>();
//
//            feisuanAirportDroneQueryWrapper.in("airport_id", page.getRecords().stream().map(i -> i.getId()).collect(Collectors.toList()));
//            List<FeisuanAirportDrone> feisuanAirportDrones1 = airportDroneMapper.selectList(feisuanAirportDroneQueryWrapper);
//
//            feisuanAirportDrones.addAll(feisuanAirportDrones1)  ;
//
//        }
//
//
//        getAirportListResponseDTOPage.setRecords(page.getRecords().stream().map(i -> {
//            String message = "风速:< " + i.getWindSpeedThreshold() + " m/s 降雨：< " + i.getRainfallThreshold() + " mm";
//            GetAirportListResponseDTO getAirportListResponseDTO = BeanUtil.copyProperties(i, GetAirportListResponseDTO.class);
//            getAirportListResponseDTO.setEnvironmentThreshold(message);
//            if (i.getStatus() == 1) {
//
//                getAirportListResponseDTO.setStatus("在线");
//            }else if (i.getStatus() == 2) {
//                getAirportListResponseDTO.setStatus("离线");
//            }
//
//            System.out.println("无人机数量=" + feisuanAirportDrones.stream().filter(i1 -> Objects.equals(i1.getAirportId(), i.getId())).collect(Collectors.toList()));
//
//            getAirportListResponseDTO.setDroneNums(Integer.valueOf(feisuanAirportDrones.stream().filter(i1 -> Objects.equals(i1.getAirportId(), i.getId())).collect(Collectors.toList()).size()).longValue());
//
//            return getAirportListResponseDTO;
//        }).collect(Collectors.toList()));
//        return getAirportListResponseDTOPage;
//    }
//
    @Override
    public Boolean editAirportInfo(EditAirportInfoRequestDTO  editAirportInfoRequestDTO) throws IOException {
//        try {
//            reentrantLock.lock();
            Long startTime = System.nanoTime();
//            System.out.println("id");
//            System.out.println(editAirportInfoRequestDTO);
//            System.out.println(editAirportInfoRequestDTO.getId());
            if (ObjectUtil.isNotNull(editAirportInfoRequestDTO)) {
                FeisuanAirportInfo feisuanAirportInfo = new FeisuanAirportInfo();
                BeanUtil.copyProperties(editAirportInfoRequestDTO, feisuanAirportInfo);
                feisuanAirportInfo.setModifyTime(LocalDateTime.now());
                airportInfoMapper.updateById(feisuanAirportInfo);
            }
            Long endTime = System.nanoTime();
//        } finally {
//            reentrantLock.unlock();
//        }

        return Boolean.TRUE;
    }
//
    @Override
    public GetAirportInfoResponseDTO getAirportInfoById(GetAirportInfoRequestDTO getAirportByIdRequestDTO) {
        if (ObjectUtil.isNotNull(getAirportByIdRequestDTO) && ObjectUtil.isNotNull(getAirportByIdRequestDTO.getId())) {
            FeisuanAirportInfo feisuanAirportInfo = airportInfoMapper.selectById(getAirportByIdRequestDTO.getId());
            GetAirportInfoResponseDTO getAirportInfoResponseDTO = BeanUtil.copyProperties(feisuanAirportInfo, GetAirportInfoResponseDTO.class);
            return getAirportInfoResponseDTO;
        }
        throw new RuntimeException("传递的参数为空");
    }
//
    @Override
    public GetAirportInfoResponseDTO getAirportInfoByGatewaySn(GetAirportInfoRequestDTO getAirportInfoRequestDTO) {
        if (ObjectUtil.isNotNull(getAirportInfoRequestDTO) && ObjectUtil.isNotNull(getAirportInfoRequestDTO.getGatewaySn())) {
            QueryWrapper<FeisuanAirportInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("gateway_sn", getAirportInfoRequestDTO.getGatewaySn()); // 使用LambdaQueryWrapper也可以，例如：LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(); queryWrapper.eq(User::getName, name);
//            return userMapper.selectOne(queryWrapper);
            FeisuanAirportInfo feisuanAirport = airportInfoMapper.selectOne(queryWrapper);
            GetAirportInfoResponseDTO getAirportInfoResponseDTO = BeanUtil.copyProperties(feisuanAirport, GetAirportInfoResponseDTO.class);
            return getAirportInfoResponseDTO;
        }
        throw new RuntimeException("传递的参数为空");
    }

//    @Override
//    public Boolean deleteAirport(Long id) {
//        if (ObjectUtil.isNull(id)) {
//            throw new RuntimeException("id不能为空");
//        }
//
//        Long startTime = System.nanoTime();
//
//        airportMapper.deleteById(id);
//
//        Long endTime = System.nanoTime();
//
//        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
//        addOperateLogRequest.setOperateModule("设备模块");
//        addOperateLogRequest.setOperateName("删除无人机设备");
//        addOperateLogRequest.setOperateResult(Boolean.TRUE);
//        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
//        addOperateLogRequest.setOperateType(1);
//        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
//        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
//        addOperateLogRequest.setTimes(endTime - startTime);
//        operateLogApi.addOperateLogRequest(addOperateLogRequest);
//
//        return Boolean.TRUE;
//    }
}
